#include "tcp_server.h"
#include "ui_tcp_server.h"
#include <QMessageBox>

tcp_server::tcp_server(QWidget* parent)
    : QWidget(parent)
    , ui(new Ui::tcp_server)
{
    ui->setupUi(this);
    m_tcpserver = new QTcpServer(this);
    m_tcpsocket = new QTcpSocket(this);
}

tcp_server::~tcp_server()
{
    delete ui;
}
void tcp_server::on_openBt_clicked()
{
    m_tcpserver->listen(QHostAddress::Any, ui->lineEdit->text().toInt());
    connect(m_tcpserver, SIGNAL(newConnection()), this, SLOT(newConnection_Slot()));

}
void tcp_server::newConnection_Slot()
{
    QMessageBox::warning(this, "连接成功", "服务器检测到新连接");
    m_tcpsocket = m_tcpserver->nextPendingConnection();
    connect(m_tcpsocket, &QTcpSocket::readyRead, this, &tcp_server::readyRead_Slot);

}

void tcp_server::readyRead_Slot()
{
    //    QString rev = m_tcpsocket->readAll();//获取客户端发送过来的信息
    //    ui->textEditRev->setText(rev);//将消息显示在接收框中
    ui->textEditRev->append(m_tcpsocket->readAll());

}


void tcp_server::on_closeBt_clicked()
{
    m_tcpserver->close();
}

void tcp_server::on_pushButton_clicked()
{
    m_tcpsocket->write(ui->textEdit_2->toPlainText().toUtf8());
    ui->textEdit_2->clear();
}
